<template>
  <div class="container">
    <Breadcrumb :items="['menu.systemManage', 'menu.systemManage.user']" />
    <a-card class="general-card onelineCard" style="height: calc(100% - 50px)">
      <a-row style="margin-bottom: 10px">
        <a-col :span="16">
          <a-space>
            <a-select
              v-model="formModel.state"
              :options="statusOptions"
              placeholder="状态"
              :style="{ width: '120px' }"
            />
            <a-select
              v-model="formModel.company_id"
              :options="companyListOptions"
              placeholder="状态"
              :style="{ width: '120px' }"
            />
            <a-select
              v-model="formModel.role_id"
              :options="roleListOptions"
              placeholder="状态"
              :style="{ width: '120px' }"
            />
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              {{ $t('searchTable.form.search') }}
            </a-button>
            <a-button @click="reset">
              {{ $t('searchTable.form.reset') }}
            </a-button>
          </a-space>
        </a-col>
        <a-col :span="8" style="text-align: right">
          <a-space>
            <a-button type="primary" @click="createRule">
              <template #icon>
                <icon-plus />
              </template>
              {{ $t('searchTable.operation.create') }}
            </a-button>
            <a-tooltip :content="$t('searchTable.actions.refresh')">
              <div class="action-icon" @click="search">
                <icon-refresh size="18" />
              </div>
            </a-tooltip>
            <a-dropdown @select="handleSelectDensity">
              <a-tooltip :content="$t('searchTable.actions.density')">
                <div class="action-icon">
                  <icon-line-height size="18" />
                </div>
              </a-tooltip>
              <template #content>
                <a-doption
                  v-for="item in densityList"
                  :key="item.value"
                  :value="item.value"
                  :class="{ active: item.value === size }"
                >
                  <span>{{ item.name }}</span>
                </a-doption>
              </template>
            </a-dropdown>
          </a-space>
        </a-col>
      </a-row>
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        :columns="(cloneColumns as TableColumnData[])"
        :data="renderData"
        :bordered="{ wrapper: true, cell: true }"
        :size="size"
        :default-expand-all-rows="true"
        ref="artable"
        @page-change="handlePaageChange"
        @page-size-change="handlePaageSizeChange"
        :scrollbar="true"
      >
        <template #state="{ record }">
          <a-switch
            type="round"
            v-model="record.state"
            :checked-value="1"
            :unchecked-value="0"
            @change="handleStatus(record)"
          >
            <template #checked>
              {{ $t(`searchTable.columns.state.enabled`) }}
            </template>
            <template #unchecked>
              {{ $t(`searchTable.columns.state.disabled`) }}
            </template>
          </a-switch>
        </template>
        <template #defaultState="{ record }">
          <a-switch
            type="round"
            v-model="record.default"
            :checked-value="true"
            :unchecked-value="false"
            disabled
          >
            <template #checked>
              {{ $t(`searchTable.columns.defaultState.default`) }}
            </template>
            <template #unchecked>
              {{ $t(`searchTable.columns.defaultState.no_default`) }}
            </template>
          </a-switch>
        </template>
        <template #operations="{ record }">
          <Icon
            icon="svgfont-bianji1"
            class="iconbtn"
            @click="handleEdit(record)"
            :size="18"
            color="#0960bd"
          ></Icon>
          <a-divider direction="vertical" />
          <a-popconfirm
            :content="t('searchTable.message.loading.delete.confirm')"
            @ok="handleDel(record)"
          >
            <Icon
              icon="svgfont-icon7"
              class="iconbtn"
              :size="18"
              color="#ed6f6f"
            ></Icon>
          </a-popconfirm>
          <a-divider direction="vertical" />
          <a-popconfirm
            :content="t('searchTable.message.loading.reset.confirm')"
            @ok="handleReset(record)"
          >
            <Icon
              icon="svgfont-zhongzhimima"
              class="iconbtn"
              :size="18"
              color="#ed6f6f"
            ></Icon>
          </a-popconfirm>
        </template>
      </a-table>
    </a-card>
    <!--表单-->
    <AddForm @register="registerModal" @success="handleData" />
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive, watch, nextTick } from 'vue';
  import useLoading from '@/hooks/loading';
  import {
    getList,
    upStatus,
    del,
    resetPassword,
  } from '@/api/systemManage/user';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import type { SelectOptionData } from '@arco-design/web-vue';

  import cloneDeep from 'lodash/cloneDeep';
  //数据
  import { columns } from './data';
  //表单
  import { useModal } from '/@/components/Modal';
  import AddForm from './AddForm.vue';
  import { useI18n } from 'vue-i18n';
  import { Icon } from '@/components/Icon';
  import { Message } from '@arco-design/web-vue';
  import { Pagination } from '@/types/global';
  import { DataItemCompany, getAllCompany } from '@/api/systemManage/company';
  import { DataItemRole, getAllRole } from '@/api/systemManage/role';

  const { t } = useI18n();
  const [registerModal, { openModal }] = useModal();
  const densityList = computed(() => [
    {
      name: t('searchTable.size.mini'),
      value: 'mini',
    },
    {
      name: t('searchTable.size.small'),
      value: 'small',
    },
    {
      name: t('searchTable.size.medium'),
      value: 'medium',
    },
    {
      name: t('searchTable.size.large'),
      value: 'large',
    },
  ]);
  //分页
  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
  };
  const pagination = reactive({
    ...basePagination,
    showTotal: true,
    showPageSize: true,
  });
  const tableHeight = document.documentElement.clientHeight - 350; //页面高度
  type SizeProps = 'mini' | 'small' | 'medium' | 'large';
  type Column = TableColumnData & { checked?: true };
  const { loading, setLoading } = useLoading(true);
  const renderData = ref([]);
  const cloneColumns = ref<Column[]>([]);
  const showColumns = ref<Column[]>([]);
  const size = ref<SizeProps>('large');

  //查询字段
  const generateFormModel = () => {
    return {
      state: 0,
      company_id: 0,
      role_id: 0,
    };
  };
  const formModel = ref(generateFormModel());
  // 公司、角色下拉数据
  const companyListOptions = ref<SelectOptionData[]>([]);
  const roleListOptions = ref<SelectOptionData[]>([]);

  // 获取公司信息
  const getCompanyList = async () => {
    try {
      const result = await getAllCompany({ state: 2 }); // state=2 代表“启用”公司
      const baseOption = [
        { label: t(`searchTable.statusOptions.all`), value: 0 },
      ];
      if (result && result.list) {
        companyListOptions.value = baseOption.concat(
          result.list.map((item: DataItemCompany) => ({
            label: item.name,
            value: item.id,
          }))
        );
      } else {
        companyListOptions.value = baseOption;
      }
    } catch (error) {
      companyListOptions.value = [{ label: '加载失败', value: 0 }];
    }
  };

  // 获取角色信息
  const getRoleList = async () => {
    try {
      const result = await getAllRole({ state: 2 }); // state=2 代表“启用”角色
      const baseOption = [
        { label: t('searchTable.statusOptions.all'), value: 0 },
      ];
      if (result && result.list) {
        roleListOptions.value = baseOption.concat(
          result.list.map((item: DataItemRole) => ({
            label: item.name,
            value: item.id,
          }))
        );
      } else {
        roleListOptions.value = baseOption;
      }
    } catch (error) {
      roleListOptions.value = [{ label: '加载失败', value: 0 }];
    }
  };

  const fetchData = async () => {
    setLoading(true);
    try {
      let params = {
        page: pagination.current,
        size: pagination.pageSize,
        ...formModel.value,
      };
      const data = await getList(params);
      renderData.value = data.list;
      pagination.current = data.page;
      pagination.total = data.total;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };

  const search = () => {
    fetchData();
    getCompanyList();
    getRoleList();
  };
  const reset = () => {
    formModel.value = generateFormModel();
    fetchData();
    getCompanyList();
    getRoleList();
  };
  getCompanyList();
  getRoleList();
  fetchData();
  const handleSelectDensity = (
    val: string | number | Record<string, any> | undefined,
    e: Event
  ) => {
    size.value = val as SizeProps;
  };

  watch(
    () => columns(t).value,
    (val) => {
      cloneColumns.value = cloneDeep(val);
      cloneColumns.value.forEach((item, index) => {
        item.checked = true;
      });
      showColumns.value = cloneDeep(cloneColumns.value);
    },
    { deep: true, immediate: true }
  );
  //添加菜单
  const createRule = () => {
    openModal(true, {
      isUpdate: false,
      record: null,
    });
  };
  //编辑数据
  const handleEdit = async (record: any) => {
    openModal(true, {
      isUpdate: true,
      record: record,
    });
  };
  //更新数据
  const handleData = async () => {
    fetchData();
  };
  //分页
  const handlePaageChange = (page: any) => {
    pagination.current = page;
    fetchData();
  };
  //分页总数
  const handlePaageSizeChange = (pageSize: any) => {
    pagination.pageSize = pageSize;
    fetchData();
  };
  //更新状态
  const handleStatus = async (record: any) => {
    try {
      Message.loading({
        content: t('searchTable.message.loading.updating'),
        id: 'upStatus',
      });
      const res = await upStatus({ id: record.id, state: record.state });
      if (res == undefined) {
        Message.success({
          content: t('searchTable.message.loading.update.successful'),
          id: 'upStatus',
        });
      }
    } catch (error) {
      Message.clear('top');
    }
  };
  //删除数据
  const handleDel = async (record: any) => {
    try {
      Message.loading({
        content: t('searchTable.message.loading.deleting'),
        id: 'upStatus',
      });
      const res = await del({ id: record.id });
      if (res == undefined) {
        fetchData();
        Message.success({
          content: t('searchTable.message.loading.delete.successful'),
          id: 'upStatus',
        });
      }
    } catch (error) {
      Message.clear('top');
    }
  };
  //重置密码
  const handleReset = async (record: any) => {
    try {
      Message.loading({
        content: t('searchTable.message.loading.resetting'),
        id: 'upStatus',
      });
      const res = await resetPassword({ user_uuid: record.user_uuid });
      if (res == undefined) {
        fetchData();
        Message.success({
          content: t('searchTable.message.loading.reset.successful'),
          id: 'upStatus',
        });
      }
    } catch (error) {
      Message.clear('top');
    }
  };
  //状态
  const statusOptions = computed<SelectOptionData[]>(() => [
    {
      label: t(`searchTable.statusOptions.all`),
      value: 0,
    },
    {
      label: t(`searchTable.columns.state.enabled`),
      value: 1,
    },
    {
      label: t(`searchTable.columns.state.disabled`),
      value: 2,
    },
  ]);
  //默认状态
  const defaultTypeOptions = computed<SelectOptionData[]>(() => [
    {
      label: t(`searchTable.statusOptions.all`),
      value: 0,
    },
    {
      label: t(`searchTable.columns.defaultState.default`),
      value: 1,
    },
    {
      label: t(`searchTable.columns.defaultState.no_default`),
      value: 2,
    },
  ]);
</script>

<script lang="ts">
  export default {
    name: 'Api',
  };
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
    height: 100%;
  }

  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }

  .action-icon {
    margin-left: 12px;
    cursor: pointer;
  }

  .active {
    color: #0960bd;
    background-color: #e3f4fc;
  }

  .setting {
    display: flex;
    align-items: center;
    width: 200px;

    .title {
      margin-left: 12px;
      cursor: pointer;
    }
  }

  :deep(.general-card > .arco-card-header) {
    padding: 10px 16px;
  }

  .iconbtn {
    user-select: none;
    cursor: pointer;
    opacity: 0.8;

    &:hover {
      opacity: 1;
    }
  }
</style>
